package com.sl.core.engine.datasource;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import org.anyline.data.datasource.DataSourceHolder;
import org.anyline.proxy.ServiceProxy;
import org.anyline.service.AnylineService;

import javax.sql.DataSource;
import java.util.Map;

public class AnylineServiceAdaptor {


    private Map<String, AnylineServiceProxy> anylineServiceProxyMap = Maps.newHashMap();


    public AnylineServiceProxy getAnyLineService(String tid, String dataSourceId, Boolean startTransactionFlag) {
        AnylineServiceProxy anyLineService = getAnyLineService(tid, dataSourceId);
        if (BooleanUtil.isTrue(startTransactionFlag)) {
            anyLineService.startTransaction();
        }
        return anyLineService;
    }

    public AnylineServiceProxy getAnyLineService(String tid, String dataSourceId) {
        String key = StrUtil.concat(true, tid, "_", dataSourceId);
        AnylineServiceProxy anylineServiceProxy = anylineServiceProxyMap.computeIfAbsent(key, (t) -> {
            DataSource dataSource = DataSourceManager.INSTANCE.getDataSource(dataSourceId, null);
            try {
                DataSourceHolder.reg(key, dataSource);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            AnylineService service = ServiceProxy.service(key);
//            AnylineDao dao = new DefaultDao();
//            service.setDao(dao);
            return new AnylineServiceProxy(service);
        });
        return anylineServiceProxy;
    }

    @SneakyThrows
    public void rollBack() {
        for (Map.Entry<String, AnylineServiceProxy> sn : anylineServiceProxyMap.entrySet()) {
            sn.getValue().rollBack();
        }
    }

    @SneakyThrows
    public void destroy() {
        for (Map.Entry<String, AnylineServiceProxy> sn : anylineServiceProxyMap.entrySet()) {
            sn.getValue().rollBack();
            DataSourceHolder.destroy(sn.getKey());
        }
        anylineServiceProxyMap.clear();
    }

    public void commit() {
        for (Map.Entry<String, AnylineServiceProxy> sn : anylineServiceProxyMap.entrySet()) {
            sn.getValue().commit();
        }
    }
}
